import { useState, useEffect } from "react";
import { Common } from 'UtilsCommon';
import { EnvConfig } from "Configs";
import PageConfigs from '../pageConfigs/index';

const _PageConfigs = {};

const pageNames = ['login', 'adminUserList', 'adminUserEdit', 'rightGroupList', 'rightGroupEdit', 'changePassword', 'pageStatisticsList', 'visitTimeStatisticsList'];
const isLocal = false;

export default (name, dispatchAction) => {
  const [pageConfig, setPageConfig] = useState(_PageConfigs[name]);

  useEffect(() => {
    if (!pageConfig) {
      const { id } = Common.getQueryString();
      let pathQuery;
      if (pageNames.includes(name)) {
        if (isLocal) {
          pathQuery = `/getconfig?name=${name}`;
        }
        else {
          pathQuery = null;
          if (PageConfigs[name]) setPageConfig(PageConfigs[name]);
        }
      }
      else pathQuery = EnvConfig.isPreview && name === "preview" ? `/getconfig?id=${id}` : `/${name.replace("_", "/")}.json`;

      if (pathQuery) {
        dispatchAction("WebService", "getConfig", { pathQuery }).then(res => {
          _PageConfigs[name] = res;
          setPageConfig(res);
        });
      }
    }
  }, [pageConfig, name, dispatchAction]);

  return pageConfig;
};
